const { validationResult } = require('express-validator');
const { UserFollow } = require('../models');
const User = require('../models/User');

class UserFollowController {
  /**
   * 切换关注用户状态
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async toggleFollow(req, res) {
    try {
      const userId = req.user.id; // 当前登录用户ID
      let targetUserId = req.params.user_id; // 被关注的用户ID
      
      console.log(`=== Controller: 切换关注状态开始 ===`);
      console.log(`当前用户ID: ${userId}, 目标用户ID(原始): ${targetUserId}, 类型: ${typeof targetUserId}`);
      
      // 确保targetUserId是数字类型
      targetUserId = parseInt(targetUserId, 10);
      console.log(`目标用户ID(转换后): ${targetUserId}, 类型: ${typeof targetUserId}`);
      
      if (isNaN(targetUserId)) {
        console.log(`目标用户ID无效: ${req.params.user_id}`);
        return res.status(400).json({ success: false, message: '无效的用户ID' });
      }
      
      // 验证用户是否存在
      console.log(`验证目标用户是否存在: ${targetUserId}`);
      const targetUser = await User.findByPk(targetUserId);
      if (!targetUser) {
        console.log(`目标用户不存在: ${targetUserId}`);
        return res.status(404).json({ success: false, message: '目标用户不存在' });
      }
      console.log(`目标用户存在: ${targetUser.username}`);
      
      // 切换关注状态 - 参数顺序已修正：followedId, followerId
      console.log(`调用UserFollow.toggleFollow方法`);
      const result = await UserFollow.toggleFollow(targetUserId, userId); // 参数顺序：被关注者，关注者
      console.log(`UserFollow.toggleFollow结果: ${JSON.stringify(result)}`);
      
      if (!result.success) {
        console.log(`切换关注状态失败: ${result.error}`);
        return res.status(400).json({ success: false, message: result.error });
      }
      
      console.log(`切换关注状态成功: ${result.message}`);
      res.json({
        success: true,
        message: result.message,
        data: {
          followed: result.followed,
          userId: targetUserId
        }
      });
    } catch (error) {
      console.error('切换关注状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 检查是否关注用户
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async checkFollowStatus(req, res) {
    try {
      const userId = req.user.id; // 当前登录用户ID
      const targetUserId = req.params.user_id; // 要检查的用户ID
      
      // 验证用户是否存在
      const targetUser = await User.findByPk(targetUserId);
      if (!targetUser) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 检查关注状态 - 参数顺序已修正：followedId, followerId
      const isFollowing = await UserFollow.isFollowing(targetUserId, userId); // 参数顺序：被关注者，关注者
      
      res.json({
        success: true,
        data: {
          userId: targetUserId,
          isFollowing
        }
      });
    } catch (error) {
      console.error('检查关注状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 获取用户的关注列表
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getFollowingList(req, res) {
    try {
      const { user_id: targetUserId } = req.params;
      const { page = 1, limit = 20 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 验证用户是否存在
      const targetUser = await User.findByPk(targetUserId);
      if (!targetUser) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 获取关注列表
      const followingList = await UserFollow.getUserFollowing(targetUserId, parseInt(limit), offset);
      
      // 获取总数
      const total = await UserFollow.getFollowingCount(targetUserId);
      
      res.json({
        success: true,
        data: {
          following: followingList.map(item => ({
            userId: item.follower_id, // 被关注者ID
            followedAt: item.created_at,
            user: item.followerUser // 已修改为followerUser
          })),
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / parseInt(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取关注列表失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 获取用户的粉丝列表
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getFollowersList(req, res) {
    try {
      const { user_id: targetUserId } = req.params;
      const { page = 1, limit = 20 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 验证用户是否存在
      const targetUser = await User.findByPk(targetUserId);
      if (!targetUser) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 获取粉丝列表
      const followersList = await UserFollow.getUserFollowers(targetUserId, parseInt(limit), offset);
      
      // 获取总数
      const total = await UserFollow.getFollowersCount(targetUserId);
      
      res.json({
        success: true,
        data: {
          followers: followersList.map(item => ({
            userId: item.followed_id, // 关注者ID
            followedAt: item.created_at,
            user: item.followedUser // 已修改为followedUser
          })),
          pagination: {
            total,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(total / parseInt(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取粉丝列表失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 获取用户的关注和粉丝数量
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getFollowStats(req, res) {
    try {
      const { user_id: targetUserId } = req.params;
      
      // 验证用户是否存在
      const targetUser = await User.findByPk(targetUserId);
      if (!targetUser) {
        return res.status(404).json({ success: false, message: '用户不存在' });
      }
      
      // 获取关注数和粉丝数
      const followingCount = await UserFollow.getFollowingCount(targetUserId);
      const followersCount = await UserFollow.getFollowersCount(targetUserId);
      
      res.json({
        success: true,
        data: {
          userId: targetUserId,
          followingCount,
          followersCount
        }
      });
    } catch (error) {
      console.error('获取关注统计失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 批量检查关注状态
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async batchCheckFollowStatus(req, res) {
    try {
      const userId = req.user.id;
      const { userIds } = req.body;
      
      if (!Array.isArray(userIds)) {
        return res.status(400).json({ success: false, message: 'userIds必须是数组' });
      }
      
      // 批量检查关注状态 - 参数顺序已修正：followedId, followerId
      const results = await Promise.all(
        userIds.map(async (targetUserId) => {
          const isFollowing = await UserFollow.isFollowing(targetUserId, userId);
          return {
            userId: targetUserId,
            isFollowing
          };
        })
      );
      
      res.json({
        success: true,
        data: results
      });
    } catch (error) {
      console.error('批量检查关注状态失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
}

module.exports = UserFollowController;